/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-08 15:43:06
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-11-05 15:56:36
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Alert,
  Row,
  Col,
  Card,
  Form,
  Input,
  Switch,
  Select,
  Icon,
  Button,
  Popconfirm,
  Table,
  Modal,
  message,
  Upload,
} from 'antd';
import SimpleTable from 'components/SimpleTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './enterprise.less';

const FormItem = Form.Item;

const { TextArea } = Input;

const { Option } = Select;

const CreateForm = Form.create()(prop => {
  const {
    companyId,
    form,
    props,
    uploadProps,
    handleCancel,
    handleUploadChange,
    state: { modalVisible, type, imageUrl, stateloading, attachmentUrl },
  } = prop;

  const { enterpriseList, dispatch } = props;
  const { getFieldDecorator, validateFields } = form;
  const { positionList, companyDetail } = enterpriseList;

  const handleChange = (e, r, k) => {
    const obj = { key: r.key };
    if (typeof e === 'string') {
      obj[k] = e;
    } else {
      obj[k] = e.target.value;
    }

    dispatch({
      type: 'enterpriseList/changePositionList',
      payload: { ...obj },
      callback: () => {},
    });
  };
  const handledeletePositionList = r => {
    dispatch({
      type: 'enterpriseList/deleteList',
      payload: r,
      callback: res => {
        if (!res.success) {
          message.warn(res.errorDesc);
        }
      },
    });
  };

  // 新增职位 按钮
  const handleAddPositionList = () => {
    dispatch({
      type: 'enterpriseList/addPositionList',
      payload: companyId,
    });
  };

  const handleOk = () => {
    validateFields((errors, values) => {
      values.logo = attachmentUrl ? attachmentUrl : values.logo;
      dispatch({
        type: type === 'edit' ? 'enterpriseList/edit' : 'enterpriseList/saveCompany',
        payload: { ...companyDetail, ...values, positionList },
        callback: res => {
          if (!res) {
            return false;
          } else if (res.success) {
            message.success(type === 'edit' ? '修改成功' : '新增成功');
            handleCancel();
            dispatch({
              type: 'enterpriseList/fetch',
              payload: {
                name: '',
                pageIndex: '1',
                pageSize: '10',
              },
            });
          } else {
            message.error(res.errorDesc);
          }
        },
      });
    });
  };
  const columns = [
    {
      title: '职位名称',
      dataIndex: 'name',
      key: 'name',
      render: (val, record) => {
        if (record.type === 'add') {
          return <Input onChange={e => handleChange(e, record, 'name')} />;
        } else if (record.type === 'edit') {
          return <Input defaultValue={val} onChange={e => handleChange(e, record, 'name')} />;
        } else {
          return <span>{val}</span>;
        }
      },
    },
    {
      title: '可体检门店类型',
      dataIndex: 'storeType',
      key: 'storeType',
      render: (val, record) => {
        if (record.type === 'add' || record.type === 'edit') {
          return (
            <Select
              placeholder="请选择"
              style={{ width: 240 }}
              defaultValue={val}
              onChange={e => handleChange(e, record, 'storeType')}
            >
              <Option key={0}>全部</Option>
              <Option key={1}>普通</Option>
              <Option key={2}>高端</Option>
            </Select>
          );
        } else {
          return <span>{val}</span>;
        }
      },
    },
    {
      title: '操作',
      render: (val, record) => (
        <Popconfirm title="确认删除?" onConfirm={() => handledeletePositionList(record)}>
          <a>删除</a>
        </Popconfirm>
      ),
    },
  ];

  const uploadButton = (
    <div>
      <Icon type={'plus'} />
      <div className="ant-upload-text">上传图片</div>
    </div>
  );

  return (
    <Modal
      title={type === 'add' ? '新增企业' : '修改企业'}
      visible={modalVisible}
      onOk={handleOk}
      onCancel={() => handleCancel()}
      className={styles.CompanyModal}
      okText="提交"
      width="850px"
      destroyOnClose
    >
      <Alert message="企业信息" type="info" />
      <Form layout="inline">
        <Row gutter={{ lg: 24 }}>
          <Col md={12} sm={24}>
            <FormItem label="企业名称" style={{ marginLeft: 12 }}>
              {getFieldDecorator('name', {
                initialValue: companyDetail?.name,
                rules: [{ required: true, message: '请输入企业名称' }],
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem label="联系地址&#12288;" style={{ marginLeft: 12 }}>
              {getFieldDecorator('address', {
                initialValue: companyDetail?.address,
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ lg: 24 }}>
          <Col md={12} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;联系人&#12288;" style={{ marginLeft: 12 }}>
              {getFieldDecorator('contactPerson', {
                initialValue: companyDetail?.contactPerson,
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem label="联系电话&#12288;" style={{ marginLeft: 12 }}>
              {getFieldDecorator('contactPhone', {
                initialValue: companyDetail?.contactPhone,
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ lg: 24 }}>
          <Col md={12} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;备注&#12288;&#12288;" style={{ marginLeft: 12 }}>
              {getFieldDecorator('remark', {
                initialValue: companyDetail?.remark,
              })(<TextArea rows={2} />)}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem label="项目负责人" style={{ marginLeft: 12 }}>
              {getFieldDecorator('customerManager', {
                initialValue: companyDetail?.customerManager,
              })(<Input placeholder="" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ lg: 24 }}>
          <Col md={12} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;公司logo" style={{ marginLeft: 12, marginTop: 10 }}>
              {getFieldDecorator('logo', {
                initialValue: companyDetail?.logo,
              })(
                <Upload {...uploadProps}>
                  {imageUrl ? (
                    <img src={imageUrl} alt="file" style={{ width: '100%' }} />
                  ) : companyDetail?.logo ? (
                    <img src={companyDetail?.logo} alt="file" style={{ width: '100%' }} />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              )}
            </FormItem>
          </Col>
        </Row>
      </Form>
      <Alert message="职务" type="info" style={{ marginTop: 20, marginBottom: 10 }} />
      <Button
        type="primary"
        icon="plus"
        style={{ marginBottom: 10 }}
        onClick={() => handleAddPositionList()}
      >
        新增
      </Button>
      <Table dataSource={positionList} columns={columns} pagination={false} />
    </Modal>
  );
});

@connect(({ enterpriseList, loading }) => ({
  enterpriseList,
  loading: loading.models.enterpriseList,
}))
@Form.create()
export default class TableList extends PureComponent {
  uploadProps = {
    name: 'file',
    action: 'https://service-api.lisonhealth.com/upload',
    showUploadList: false,
    headers: {
      Authorization: localStorage.getItem('authorization-token'),
    },
    listType: 'picture-card',
    onChange: info => {
      const { form } = this.props;
      if (info.file.status === 'uploading') {
        this.setState({ stateloading: true });
        return;
      }
      if (info.file.status === 'done') {
        const { success } = info.file.response;
        if (success) {
          message.success(`导入成功.`);
          this.getBase64(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              stateloading: false,
            })
          );
          const {
            file: {
              response: { data },
            },
          } = info;
          this.setState({
            attachmentUrl: data,
          });
          form.setFieldsValue({ logo: data });
        } else {
          message.success(`导入失败.`);
        }
      } else if (info.file.status === 'error') {
        message.error(`上传文件失败.`);
      }
    },
  };

  state = {
    modalVisible: false,
    type: '',
    companyId: '',
    imageUrl: '',
    stateloading: '',
    attachmentUrl: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'enterpriseList/fetch',
      payload: {
        name: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });
  }

  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  // 分页
  handleStandardTableChange = pagination => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const params = {
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
        name: values.name,
      };

      dispatch({
        type: 'enterpriseList/fetch',
        payload: params,
      });
    });
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'enterpriseList/fetch',
      payload: {
        name: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      const params = {
        pageIndex: 0,
        pageSize: 10,
        name: values.name,
      };

      dispatch({
        type: 'enterpriseList/fetch',
        payload: params,
      });
    });
  };

  handleEdit = r => {
    const { dispatch } = this.props;

    dispatch({
      type: 'enterpriseList/detail',
      payload: {
        id: r?.id,
      },
      callback: res => {
        if (res.success) {
          this.setState({
            type: 'edit',
            modalVisible: true,
            companyId: r.id,
          });
          dispatch({
            type: 'enterpriseList/editPositionList',
            payload: r,
          });
        } else {
          message.error('请求错误');
        }
      },
    });
  };

  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'enterpriseList/addCompany',
    });
    this.setState({
      type: 'add',
      modalVisible: true,
    });
  };

  showpic = v => {
    window.open(v);
  };

  reColumns = () => {
    const that = this;
    return [
      {
        title: '企业名称',
        dataIndex: 'name',
      },
      {
        title: '联系地址',
        dataIndex: 'address',
      },
      {
        title: '项目负责人',
        dataIndex: 'customerManager',
      },
      {
        title: '联系电话',
        dataIndex: 'contactPhone',
      },
      {
        title: '备注',
        dataIndex: 'remark',
      },
      {
        title: '创建人',
        dataIndex: 'createUserName',
      },
      {
        title: '企业logo',
        dataIndex: 'logo',
        render: v => (
          <a href={v} target="_blank">
            <Icon type="picture" theme="filled" />
          </a>
        ),
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: v => (
          <Switch
            checkedChildren="开"
            unCheckedChildren="关"
            defaultChecked={v === '1'}
            disabled="false"
          />
        ),
      },
      {
        title: '操作',
        render: (val, record) => <a onClick={() => that.handleEdit(record)}>修改</a>,
      },
    ];
  };

  renderSearchForm = () => {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('name')(
                <Input style={{ width: '100%' }} placeholder="请输入企业名称" />
              )}
            </FormItem>
          </Col>
          <Col md={16} sm={24}>
            <div
              style={{
                overflow: 'hidden',
                height: '40px',
                lineHeight: '40px',
              }}
            >
              <span
                style={{
                  float: 'right',
                }}
              >
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  style={{
                    marginLeft: 8,
                  }}
                  onClick={this.handleFormReset}
                >
                  重置
                </Button>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const columns = this.reColumns();
    const {
      enterpriseList: { data },
      loading,
    } = this.props;

    const { modalVisible, type, companyId } = this.state;

    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <div>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
            <div>
              <Button type="primary" icon="plus" onClick={this.handleAdd}>
                新增
              </Button>
            </div>
            <SimpleTable
              selectedRows={false}
              loading={loading}
              data={data}
              columns={columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...this} modalVisible={modalVisible} type={type} companyId={companyId} />
      </PageHeaderLayout>
    );
  }
}
